package com.xingzhi.common.util;

import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSONObject;
import com.qiniu.cdn.CdnManager;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.processing.OperationManager;
import com.qiniu.storage.Configuration;
import com.qiniu.util.Auth;
import com.qiniu.util.StringMap;
import com.qiniu.util.UrlSafeBase64;
import com.xingzhi.common.constant.Const;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by daniel.luo on 2018/5/23.
 */
@Component
public class QiNiuUtil {
    public static String getToken() throws Exception {
        try (Jedis jedis = RedisUtil.getJedis()) {
            String token = jedis.get(Const.QINIU_TOKEN);
            if (StringUtils.isEmpty(token)) {
                token = generateToken();
                //略小于七牛云的默认一小时时间
                jedis.setex(Const.QINIU_TOKEN, 3500, token);
                return token;
            } else return token;
        }
    }

    public static String generateToken() throws Exception {
        String accessKey = Const.AK;
        String secretKey = Const.SK;
        String bucket = Const.BUCKET_NAME;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
        System.out.println(upToken);
        return upToken;
    }

    public static int getVedioLength(String keyId) throws Exception {
        String ret = SampleHttpUtil.getResult(Const.DOMAIN + keyId + "?avinfo");
        JSONObject jo = JSONObject.parseObject(ret);
        JSONObject joFormat = jo.getJSONObject("format");
        int len = -1;
        if (null != joFormat) {
            String duration = joFormat.getString("duration");
            if (StringUtils.isEmpty(duration)) return len;
            else {
                len = Double.valueOf(duration).intValue();
                System.out.println("len : " + len);
                return len;
            }
        } else return len;
    }

    public static String getAntiLeechAccBasedOnTS(String host, String fileName, StringMap queryStringMap, String encryptKey, long deadline) throws Exception {
        String signedUrl = CdnManager.createTimestampAntiLeechUrl(host, fileName,
                queryStringMap, encryptKey, deadline);
        System.out.println(signedUrl);
        return signedUrl;
    }

    public static Map<String, String> encryptOneVideo(String key) throws Exception {
        String pwdStr = HashUtil.generateRandomStr(16);
        String pwd = UrlSafeBase64.encodeToString(pwdStr);
        System.out.println("key : " + key);
        String mp4SaveEntry = String.format("%s:%s", Const.BUCKET_NAME, key + ".m3u8");
        String fopMp4 = String.format("avthumb/m3u8/noDomain/1/vcodec/copy/acodec/copy/hlsKey/" + pwd + "/hlsKeyUrl/helo/hlsMethod/qiniu-protection-10|saveas/%s",
                UrlSafeBase64.encodeToString(mp4SaveEntry));
        System.out.println("mp4SaveEntry : " + mp4SaveEntry);
        try {
            Configuration cfg = new Configuration(Zone.zone0());
            Auth testAuth = Auth.create(Const.AK, Const.SK);
            OperationManager operationManager = new OperationManager(testAuth, cfg);
            String id = operationManager.pfop(Const.BUCKET_NAME, key, fopMp4, Const.PIPELINE, Const.NOTIFY, true);
            // TODO insert db step 1, encrypt_time, err_count, encrypt_key, encrypt_pwd
            Map<String, String> mapParam = new HashMap<String, String>();
            mapParam.put("url", Const.DOMAIN + key);
            mapParam.put("encrypt_pwd", pwdStr);
            mapParam.put("encrypt_key", key + ".m3u8");
            mapParam.put("encrypt_time", TimeUtil.getDateTime(0));
//            cmsService.setEncryptInfo(mapParam);
            String purl = "http://api.qiniu.com/status/get/prefop?id=" + id;
            System.out.println(purl);
            return mapParam;
        } catch (QiniuException e) {
            e.printStackTrace();
            return null;
        }
    }
}
